package com.tiancheng.trade.order.feign;

import com.tiancheng.trade.commom.web.http.PlatformRequest;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.order.feign.dto.DeductionPayCheckDTO;
import com.tiancheng.trade.order.util.DeductionCheckConfig;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: likailun
 * @Description:
 * @Date: create in 2023/3/8 11:16
 */
@Component
@Slf4j
public class DeductionPayCheckService {

    @Resource
    private DeductionCheckConfig deductionCheckConfig;


    @Resource
    private PlatformRequest platformRequest;

    /**
     * 校验零元抵扣订单真实性
     *
     * @return
     */
    public Boolean deductionPayCheck(DeductionPayCheckDTO dto) {
        log.info("校验零元抵扣订单真实性 params:{}", JsonUtil.toJsonString(dto));
        try {
            String url = deductionCheckConfig.getUrl(dto.getOrderSource(), "");
            Result result = platformRequest.jsonPostRequest(url, JsonUtil.fromJson(JsonUtil.toJsonString(dto), Map.class), this.getTokenHeader());
            Map<String, Object> resultMap = JsonUtil.fromJson(result.toString(), Map.class);
            log.info("校验零元抵扣订单真实性 result:{}", JsonUtil.toJsonString(resultMap));
            return MapUtils.isNotEmpty(resultMap) && MapUtils.getInteger(resultMap, "ret").equals(0);
        } catch (Exception e) {
            log.error("校验零元抵扣订单真实性异常:" + e.getMessage(), e);
            return false;
        }
    }


    /**
     * 获取优惠券服务的token
     *
     * @return
     */
    private Header getTokenHeader() {
        String token = platformRequest.getAccessToken();
        return new BasicHeader("token", token);
    }

}
